package com.gitee.limaozhi.socket.lesson02.example3;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

/**
 * 换行分隔解码器
 *
 * @author hzlimaozhi
 * @date 2019/08/23 17:41
 */
public class LineDelimiterDecoder {

    private static final char DELIMITER = '\n';

    private LinkedList<byte[]> queue = new LinkedList<>();
    // 上次decode剩余的半包
    private byte[] left = null;
    private int leftStart = 0;

    /**
     * @param newBytes read()读取的字节数组
     */
    public synchronized List<String> decode(byte[] newBytes) {
        queue.addLast(newBytes);

        List<String> result = new ArrayList<>();

        Iterator<byte[]> iterator = queue.iterator();
        while (iterator.hasNext()) {
            byte[] bytes = iterator.next();
            iterator.remove();

            int start = 0;
            for (int index = 0; index < bytes.length; index++) {
                if (bytes[index] == DELIMITER) {
                    // 拆包
                    int leftLength = left != null ? left.length - leftStart : 0;
                    int itemLength = index - start;
                    int length = leftLength + itemLength;
                    if (length > 0) {
                        // 粘包
                        byte[] item = new byte[length];
                        if (leftLength > 0) {
                            System.arraycopy(left, leftStart, item, 0, leftLength);
                        }
                        if (itemLength > 0) {
                            System.arraycopy(bytes, start, item, leftLength, itemLength);
                        }
                        result.add(new String(item));
                    }

                    left = null;
                    start = index + 1;
                }
            }

            if (start != bytes.length) {
                left = bytes;
                leftStart = start;
            }
        }
        return result;
    }

}
